package com.njitt.bysj.srevice;

import com.njitt.bysj.base.BaseService;
import com.njitt.bysj.base.ResultInfo;
import com.njitt.bysj.bean.LoginBean;
import com.njitt.bysj.bean.RoleBean;
import com.njitt.bysj.mapper.EmpBeanMapper;
import com.njitt.bysj.mapper.LoginBeanMapper;
import com.njitt.bysj.model.EmpModel;
import com.njitt.bysj.utils.AssertUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description: 登录
 * @author: wyj
 * @time: 2022/3/18 20:13
 */
@Service
public class LoginService extends BaseService<LoginBean, Integer> {
    @Resource
    private LoginBeanMapper loginMapper;
    @Resource
    private EmpBeanMapper empMapper;

    public ResultInfo queryUserByAccount(UsernamePasswordToken token, boolean rememberMe) {
        AssertUtil.isTrue(StringUtils.isBlank(token.getUsername()), "用户名不能为空");
        token.setRememberMe(true);
        Subject subject = SecurityUtils.getSubject();
        ResultInfo resultInfo = new ResultInfo();
        try {
            subject.login(token);
            EmpModel empModel = (EmpModel) subject.getPrincipals().iterator().next();
            System.out.println(empModel);
            List<String> roles = empModel.getRoles();
            if (roles.contains("admin")) {
                resultInfo.setMsg("success");
                resultInfo.setCode(100);
            } else {
                resultInfo.setCode(200);
                resultInfo.setMsg("success");
            }
        } catch (UnknownAccountException e) {
            resultInfo.setCode(500);
            resultInfo.setMsg("登录失败");
        } catch (IncorrectCredentialsException e) {
            e = new IncorrectCredentialsException("密码错误");
            resultInfo.setCode(500);
            resultInfo.setMsg(e.getMessage());
        }
        return resultInfo;
    }

    public LoginBean loginUser(String account) {
        AssertUtil.isTrue(StringUtils.isBlank(account), "用户名不能为空");
        return loginMapper.queryUserByAccount(account);
    }

}
